package leetcode;

/**
 * @author niann
 * @description  //TODO 相交链表 https://leetcode.cn/problems/intersection-of-two-linked-lists/description/
 *
 * @since 2024/10/24 18:17
 **/
public class LeetCode160 {
      public class ListNode {
          int val;
          ListNode next;
          ListNode(int x) {
              val = x;
              next = null;
          }
      }
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            var ACur = headA;
            var BCur = headB;
            while (ACur!=null){
                while (BCur!=null){
                    if (ACur.hashCode()==BCur.hashCode()){
                        return ACur;
                    }
                    BCur=BCur.next;
                }
                ACur = ACur.next;
                BCur = headB;
            }
            return null;
        }

        /**
         * 双指针
         * @param headA
         * @param headB
         * @return
         */
        public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
            if (headA == null || headB == null) {
                return null;
            }

            ListNode ACur = headA;
            ListNode BCur = headB;

            // 如果两个指针相等，则返回该节点；否则继续
            while (ACur != BCur) {
                // 如果当前A指针到达链表末尾，则重置为B链表的头节点
                ACur = (ACur == null) ? headB : ACur.next;
                // 如果当前B指针到达链表末尾，则重置为A链表的头节点
                BCur = (BCur == null) ? headA : BCur.next;
            }

            // 最后，返回相交的节点（或null）
            return ACur;
        }
    }
}
